package com.ruoyi.custom.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.custom.domain.StoreProductAttrValue;
import com.ruoyi.custom.mapper.StoreProductAttrValueMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.custom.mapper.StoreProductMapper;
import com.ruoyi.custom.domain.StoreProduct;
import com.ruoyi.custom.service.IStoreProductService;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.jws.Oneway;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-12
 */
@Service
public class StoreProductServiceImpl implements IStoreProductService {
    @Resource
    private StoreProductMapper storeProductMapper;

    @Resource
    private StoreProductAttrValueMapper storeProductAttrValueMapper;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public StoreProduct selectStoreProductById(Long id) {
        return storeProductMapper.selectStoreProductById(id);
    }

    /**
     * 查询商品列表
     *
     * @param storeProduct 商品
     * @return 商品
     */
    @Override
    public List<StoreProduct> selectStoreProductList(StoreProduct storeProduct) {
        List<StoreProduct> storeProducts = storeProductMapper.selectStoreProductList(storeProduct);
        for (StoreProduct product : storeProducts) {
            StoreProductAttrValue storeProductAttrValue = new StoreProductAttrValue();
            storeProductAttrValue.setProductId(String.valueOf(product.getId()));
            List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueMapper.selectStoreProductAttrValueList(storeProductAttrValue);
            product.setStoreProductAttrValueList(storeProductAttrValueList);
        }
        return storeProducts;
    }

    /**
     * 新增商品
     *
     * @param storeProduct 商品
     * @return 结果
     */
    @Override
    public int insertStoreProduct(StoreProduct storeProduct) {
        Long userId = SecurityUtils.getUserId();
        storeProduct.setCreateTime(DateUtils.getNowDate());
        storeProduct.setMerId(String.valueOf(userId));
        storeProduct.setCustomForm(storeProduct.getTableData());
        storeProductMapper.insertStoreProduct(storeProduct);
        JSONArray jsonArray = JSONArray.parseArray(storeProduct.getTableData());
        List<StoreProductAttrValue> storeProductAttrValueList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
            String uniValue = IdUtil.getSnowflakeNextIdStr();
            jsonObject.put("uniqueValue", uniValue);
            StoreProductAttrValue storeProductAttrValue = new StoreProductAttrValue();
            storeProductAttrValue.setProductId(storeProduct.getId().toString());
            storeProductAttrValue.setSpecs(String.valueOf(jsonObject.get("specs")));
            storeProductAttrValue.setStock(String.valueOf(jsonObject.get("stock")));
            storeProductAttrValue.setPrice(new BigDecimal(jsonObject.get("price").toString()));
            storeProductAttrValue.setImage(String.valueOf(jsonObject.get("image")));
            storeProductAttrValue.setUniqueValue(uniValue);
            storeProductAttrValue.setCost(new BigDecimal(jsonObject.get("cost").toString()));
            storeProductAttrValue.setOtPrice(new BigDecimal(jsonObject.get("otPrice").toString()));
            storeProductAttrValue.setWeight(new BigDecimal(jsonObject.get("weight").toString()));
            storeProductAttrValue.setVolume(new BigDecimal(jsonObject.get("volume").toString()));
            storeProductAttrValueList.add(storeProductAttrValue);
            jsonArray.set(i, jsonObject);
        }
        storeProduct.setCustomForm(jsonArray.toString());
        storeProductMapper.updateStoreProduct(storeProduct);
        return storeProductAttrValueMapper.insertBatchStoreProductAttrValue(storeProductAttrValueList);
    }

    /**
     * 修改商品
     *
     * @param storeProduct 商品
     * @return 结果
     */
    @Override
    public int updateStoreProduct(StoreProduct storeProduct) {
        storeProduct.setUpdateTime(DateUtils.getNowDate());
        storeProduct.setCustomForm(storeProduct.getTableData());
        JSONArray jsonArray = JSONArray.parseArray(storeProduct.getTableData());
        List<String> delUniqueValueList = new ArrayList<>();

        //是否有删除的
        if (!ObjectUtils.isEmpty(storeProduct.getDelTableDataUniqueValueList())) {
            JSONArray arr = JSONArray.parseArray(storeProduct.getDelTableDataUniqueValueList());
            for (int i = 0; i < arr.size(); i++) {
                delUniqueValueList.add(String.valueOf(arr.get(i)));
                storeProductAttrValueMapper.deleteStoreProductAttrValueByUniqueValue(String.valueOf(arr.get(i)));
            }
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
            String uniqueValue = String.valueOf(jsonObject.get("uniqueValue"));

            //是否有删除的
            if (delUniqueValueList.contains(uniqueValue)) {
                jsonArray.remove(i);
                continue;
            }

            //对比下有没有修改
            StoreProductAttrValue storeProductAttrValue1 = storeProductAttrValueMapper.selectStoreProductAttrValueByUniqueValue(uniqueValue);
            StoreProductAttrValue storeProductAttrValue2 = CglibUtil.copy(storeProductAttrValue1, StoreProductAttrValue.class);
//            storeProductAttrValue2.setSpecs(Optional.ofNullable(String.valueOf(jsonObject.get("specs"))).orElse(""));
            storeProductAttrValue2.setStock(ObjectUtils.isEmpty(jsonObject.get("stock")) ? "0" : String.valueOf(jsonObject.get("stock")));
            storeProductAttrValue2.setPrice(new BigDecimal(Optional.ofNullable(jsonObject.get("price")).orElse("0").toString()));
            storeProductAttrValue2.setImage(ObjectUtils.isEmpty(jsonObject.get("image")) ? "" : String.valueOf(jsonObject.get("image")));
            storeProductAttrValue2.setCost(new BigDecimal(Optional.ofNullable(jsonObject.get("cost")).orElse("0").toString()));
            storeProductAttrValue2.setOtPrice(new BigDecimal(Optional.ofNullable(jsonObject.get("otPrice")).orElse("0").toString()));
            storeProductAttrValue2.setWeight(new BigDecimal(Optional.ofNullable(jsonObject.get("weight")).orElse("0").toString()));
            storeProductAttrValue2.setVolume(new BigDecimal(Optional.ofNullable(jsonObject.get("volume")).orElse("0").toString()));
            if (!storeProductAttrValue1.equals(storeProductAttrValue2)) {
                storeProductAttrValueMapper.updateStoreProductAttrValue(storeProductAttrValue2);
            }
        }
        storeProduct.setCustomForm(jsonArray.toString());
        storeProductMapper.updateStoreProduct(storeProduct);

        return storeProductMapper.updateStoreProduct(storeProduct);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteStoreProductByIds(Long[] ids) {
        return storeProductMapper.deleteStoreProductByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteStoreProductById(Long id) {
        return storeProductMapper.deleteStoreProductById(id);
    }

    @Override
    public int deleteStoreProductByIdsUpd(Long[] ids) {
        return storeProductMapper.deleteStoreProductByIdsUpd(ids);
    }
}
